from django.db import models
from books.models import Book
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _

DEPS = (
	('A', 'CEO/CTO'),
	('B', 'DEV'),
	('C', 'OTHERS'),
)

STAT = (
	('A', 'Abandon'),
	('B', 'Break'),
	('C', 'Continue'),
)

class BookProfile(models.Model):
    '''Book status and manager'''
    book = models.OneToOneField(Book)
    num_available = models.IntegerField(_('number of available'), default=-1)
    num_reserving = models.IntegerField(_('number of reserving'), default=0)
    num_total = models.IntegerField(_('number of total'), default=-1)
	
    def __unicode__(self):
        return self.book.title

    def is_available(self):
        return bool(self.num_available)

    def get_status(self):
        return self.num_available, self.num_total, self.num_reserving

class UserProfile(models.Model):
	'''More details of User/Reader'''
	user = models.OneToOneField(User)
	department = models.CharField(_('department'), max_length=1, choices=DEPS)
	reading_books = models.ManyToManyField(BookProfile, through='Reading', related_name='books_read')
	reserving_books = models.ManyToManyField(BookProfile, through='Reserving', related_name='books_reserved')

	def __unicode__(self):
		return self.user.username

	def save_m2m(self, request, *args, **kwargs):
		if self.user != request.user:
			self.user = request.user

		u = super(UserProfile, self).save_m2m(request, *args, **kwargs)
		return u

class Reading(models.Model):
	'''intermediary of reading relations'''
	status = models.CharField(_('reading status'), max_length=1, choices=STAT, default='C')
	from_date = models.DateField(auto_now_add=True) # side effect: editable=False, blank=True
	to_date = models.DateField(auto_now=True)
	user_reading = models.ForeignKey(UserProfile)
	book_read = models.ForeignKey(BookProfile)

	def __unicode__(self):
		if self.status == 'C':
			return '%s is reading %s (from %s)' % (self.user_reading.user.username, self.book_read.book.title, self.from_date)
		elif self.status == 'B':
			return '%s wanna give back %s @ %s' % (self.user_reading.user.username, self.book_read.book.title, self.to_date)
		else:
			return 'The reading has been abandoned'

class Reserving(models.Model):
	'''intermediary of reserving relations'''
	status = models.CharField(_('reserving status'), max_length=1, choices=STAT, default='C')
	time = models.DateTimeField(auto_now_add=True)
	user_reserving = models.ForeignKey(UserProfile)
	book_reserved = models.ForeignKey(BookProfile)

	def __unicode__(self):
		if self.status == 'C':
			return '%s is reserving %s (from %s)' % (self.user_reserving.user.username, self.book_reserved.book.title, self.time)
		elif self.status == 'B':
			return '%s has cancelled the reserving of %s' % (self.user_reserving.user.username, self.book_reserved.book.title)
		else:
			return '%s has been lent out @ %s' % (self.book_reserved.book.title, self.time)
